import { BasicDecoder } from './BasicDecoder';

export class Address {
  public ip: string;
  public port: number;

  public static fromString(str: string | String): Address {
    let addr = new Address();
    let arr = str.split(":");
    addr.ip = arr[0];
    addr.port = parseInt(arr[1]);
    return addr;
  }

  public toString() {
    return this.ip + ":" + this.port;
  }
}

let wifiReadAble = false;

export enum Type { //TCP 中local代表客户端，remote代表服务端
  local = "local", remote = "remote"
}

export abstract class BasicNetworkUtil {
  protected type: Type = null;
  protected decoder: BasicDecoder = null;
  protected address: Address = new Address();

  //type 必须是local或者remote
  constructor(decoder: BasicDecoder, type: Type, address: Address) {
    this.decoder = decoder;
    this.type = type;
    this.address = address;
  }


  public  abstract init();

  public abstract recv(callback: (data: Map<string, number>) => void): void;

  public abstract recvBinary(callback: (buffer: ArrayBuffer) => void): void;

  public abstract send(sendDataString: string | ArrayBuffer);

  public abstract close();

  public async setAddress(address: Address) {
    this.close();
    this.address = address;
    this.init();
  }

  public getAddress(): Address {
    let addr = new Address();
    addr.ip = this.address.ip;
    addr.port = this.address.port;
    return addr;
  }
}